package pl.koziolekweb.szkola.EHRegExFun;

// EH-RegExFun/RegExFuns.java
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExFuns {
    public static void main(String[] args) {
        File file = new File("RegExFuns.dat");
        if (!(file.exists()  && file.isFile() &&
              file.canRead())) {
            System.out.println("No such file: " +
                                file.getName());
            System.exit(1);
        }

        // reading file into one string
        StringBuilder sb = new StringBuilder(2000);
        BufferedReader br = null;
        try {
            br = new BufferedReader(
                     new FileReader(file));
            String line;
            while ( (line = br.readLine()) != null)
                sb.append(line + "\n");
            br.close();
        } catch (IOException e) {
            System.out.println("Troubles reading file");
            e.printStackTrace();
            System.exit(1);
        } finally {
            if (br != null) {
                try {br.close();}
                catch(IOException ignore) { }
            }
        }
        String text = sb.toString();

        // removing '//' comments
        text = text.replaceAll("(?m)//.*$","");
        // removing '/* ... */' multiline comments
        text = text.replaceAll("(?ms)/\\*.*?\\*/"," ");

        // pattern of identifier
        String id = "\\b[a-zA-Z_][\\w]*";
        // pattern of declaration ('int k'
        // or 'java.lang.String[] s' etc.)
        String de = "ID(\\.ID)*(\\s*\\[\\s*\\])?\\s+ID".
                    replace("ID",id);

        // pattern of function declaration
        String patString =
            ("^\\s*(ID\\s*)+" +
             "\\(" +
             "(\\s*|" +
             "\\s*DE(\\s*,\\s*DE\\s*)*\\s*)" +
             "\\)").replace("ID",id).replace("DE",de);

        Matcher mtext =
            Pattern.compile(patString,
                Pattern.MULTILINE | Pattern.DOTALL).
                matcher(text);

        // with this we will replace sequences of
        // white chars with exactly one space
        Matcher mspac =
            Pattern.compile("\\s+",
                Pattern.MULTILINE | Pattern.MULTILINE).
                matcher("");

        boolean found = mtext.find();
        while (found) {
            String g = mtext.group();
            g = mspac.reset(g).replaceAll(" ");
            System.out.println(g.trim());

            found = mtext.find();
        }
    }
}